package com.hundsun.yr.universal.p2p.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.Utils.HeaderMap;
import com.hundsun.yr.universal.library.base.BaseWebActivity;
import com.hundsun.yr.universal.library.base.BaseWebActivity.LoadType;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.netstatus.NetUtils.NetType;
import com.hundsun.yr.universal.library.utils.HsNumberUtils;
import com.hundsun.yr.universal.library.utils.MathUtils;
import com.hundsun.yr.universal.library.view.BrowserLayout;
import com.hundsun.yr.universal.library.view.hsdialog.HSDialog;
import com.hundsun.yr.universal.library.widget.HSButton;
import com.hundsun.yr.universal.library.widget.HSToast;
import com.hundsun.yr.universal.p2p.bean.AdSlideBeen;
import com.hundsun.yr.universal.p2p.bean.AuthorizationDetailBean;
import com.hundsun.yr.universal.p2p.bean.BankAccountBeen;
import com.hundsun.yr.universal.p2p.bean.ManeBean;
import com.hundsun.yr.universal.p2p.bean.ProductBeen;
import com.hundsun.yr.universal.p2p.bean.UpdatePayPwdBeen;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.Container;
import com.hundsun.yr.universal.p2p.config.Extras;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.InitializePresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseActivity;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.utils.Logs;
import com.hundsun.yr.universal.p2p.view.base.BaseItemView;
import com.hundsun.yr.universal.p2p.widget.CalculatorView;
import com.hundsun.yr.universal.p2p.widget.HorizontalProgressBarWithNumber;
import com.hundsun.yr.universal.p2p.widget.MyWebView;
import com.hundsun.yr.universal.p2p.widget.PullUpToLoadMore;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

/**
 * @version V1.0
 * @Title: ProjectDetailsActivity.java
 * @Description: 项目详情页面
 * TODO 详情页面--修改很多地方
 * @date 2015-12-3 上午9:57:00
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 */
public class InvestDetailsActivity extends BaseActivity implements BaseItemView, OnClickListener, HSDialog.HSDialogOnItemClickListener {

    /**
     * 购买button
     **/
    private HSButton btn_buy = null;
    /**
     * 软件盘弹起后所占高度阀值
     **/
    private int keyHeight = 0;

    /**
     * 年化收益
     **/
    private TextView tv_percent = null;
    /**
     * 新人专享图标
     **/
    private ImageView iv_new_exclusive = null;
    /**
     * 底部视图
     **/
    private LinearLayout linear_botton = null;
    /**
     * 起购金额
     **/
//    private TextView tv_addmoney = null;
    /**
     * 投资期限
     **/
    private TextView tv_duration = null;
    /**
     * 投资期限单位
     **/
    private TextView tv_duration_txt = null;
    /**
     * 项目规模
     **/
    private TextView tv_scale = null;
    /**
     * 购买按钮
     **/
//    private HSButton btn_no_buy = null;

    private TextView hstv_selected_product = null;

    /**
     * 新人专享
     */
    private TextView hstv_new_exclusive = null;

    /**
     * 加息利率
     */
    private TextView hstv_raise_interest_rate = null;
    /**
     * 活动
     */
    private TextView hstv_raise_interest_event = null;
    /**
     * 起投金额
     **/
    private String startMoney;

    /**
     * 营销商品名称
     **/
    private String mktGdsName;
    /**
     * 利率
     **/
    private String rate;
    /**
     * 投资时间
     **/
    private String ivstime;

    /**
     * 跳转标识
     **/
    private String TAG = "";
    private HSDialog dialog;
    private ProductBeen productBeen = null;
    private String zwgt_data;
    private PopupWindow popWindow;
    private ImageView iv_calculator = null;
    private CalculatorView calculator = null;
    private HorizontalProgressBarWithNumber invest_progress = null;
    private TextView tv_surplus_invest = null;
    private TextView tv_raise_time = null;
    private TextView tv_start_time = null;
    private TextView tv_end_time = null;
    private LinearLayout ll_risk_guarantee = null;
    //    private LinearLayout ll_product_detail = null;
//    private LinearLayout ll_product_subject_message = null;
//    private LinearLayout ll_invest_record = null;
    private HSDialog paypwdDialog;
    private RequestPresenter mPresenter = null;
    private Bundle bundle;
    private PullUpToLoadMore putlm = null;
    private MyWebView detail_webview = null;
    private TextView tv_product_risk_level = null;
    private TextView tv_risk_desc = null;
    private RatingBar rb_product_star = null;
    private TextView tv_star_desc = null;
    private LinearLayout ll_star_desc = null;
    private TextView tv_product_star = null;
    private boolean mIsShowStarDesc = false;

    private boolean TASK_PAYMENTAUTHDETAIL = false;
    private boolean TASK_REPAYAUTHDETAIL = false;

    @Override
    protected boolean isApplyKitKatTranslucency() {
        // TODO Auto-generated method stub
        return false;
    }

    /**
     * 获取bundle传递过来的数据
     *
     * @param extras
     */
    @Override
    protected void getBundleExtras(Bundle extras) {
        // TODO Auto-generated method stub
        TAG = extras.getString(Extras.NAVIGATE_TAG);//跳转标识，说明是由列表点进来的
        productBeen = (ProductBeen) extras.getSerializable(Extras.DATA);
        /**投资产品名称**/
        mktGdsName = productBeen.name;
    }

    @Override
    protected int getContentViewLayoutID() {
        // TODO Auto-generated method stub
        return R.layout.act_invest_detail;
    }

    /**
     * 获取event数据
     *
     * @param eventCenter
     */
    @Override
    protected void onEveComming(@SuppressWarnings("rawtypes") EventCenter eventCenter) {
        // TODO Auto-generated method stub
        switch (eventCenter.getEventCode()) {
            case Extras.SYSTEM_TIME_REFRESH:
                if (productBeen != null) {
                    productBeen.refreshStatus(mContext, btn_buy, invest_progress, productBeen.dispalyProgress(), tv_surplus_invest, productBeen.product_status);//刷新状态
                }

                break;
            default:
                break;
        }
    }

    @Override
    protected boolean isBindEventBusHere() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    protected View getLoadingTargetView() {
        // TODO Auto-generated method stub
        return null;
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void initViewsAndEvents() {
        // TODO Auto-generated method stub
        //点开的时候赋值一次时间
        Container.getInstance().setSystemTime(System.currentTimeMillis() + "");
        setToolbarTitle(mktGdsName);
        toolbar_title.setTextColor(Color.WHITE);
        mToolbar.setNavigationIcon(R.drawable.icon_back);
        mToolbar.setBackgroundColor(Color.parseColor("#FA5B2C"));

        btn_buy = findView(R.id.btn_buy);
        btn_buy.setOnClickListener(this);

        hstv_selected_product = findView(R.id.hstv_selected_product);
        hstv_new_exclusive = findView(R.id.hstv_new_exclusive);
        hstv_raise_interest_rate = findView(R.id.hstv_raise_interest_rate);
        hstv_raise_interest_event = findView(R.id.hstv_raise_interest_event);

        btn_buy.setEnabled(false);

        iv_new_exclusive = findView(R.id.iv_new_exclusive);
//        tv_addmoney = findView(R.id.tv_addmoney);
        tv_duration = findView(R.id.tv_duration);
        tv_duration_txt = findView(R.id.tv_duration_txt);
        tv_scale = findView(R.id.tv_scale);
        invest_progress = findView(R.id.invest_progress);
        tv_surplus_invest = findView(R.id.tv_surplus_invest);
        tv_raise_time = findView(R.id.tv_raise_time);
        tv_start_time = findView(R.id.tv_start_time);
        tv_end_time = findView(R.id.tv_end_time);
        tv_percent = findView(R.id.tv_percent);
        ll_risk_guarantee = findView(R.id.ll_risk_guarantee);
        putlm = findView(R.id.putlm);
        detail_webview = findView(R.id.detail_webview);
        tv_product_risk_level = findView(R.id.tv_product_risk_level);
        tv_risk_desc = findView(R.id.tv_risk_desc);
        rb_product_star = findView(R.id.rb_product_star);
        LayerDrawable progressDrawable = (LayerDrawable) rb_product_star.getProgressDrawable();
        progressDrawable.getDrawable(2).setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
//        progressDrawable.getDrawable(1).setColorFilter(Color.YELLOW, PorterDuff.Mode.SRC);

        tv_star_desc = findView(R.id.tv_star_desc);
        ll_star_desc = findView(R.id.ll_star_desc);
        tv_product_star = findView(R.id.tv_product_star);
        tv_product_star.setOnClickListener(this);

        //添加头
        String zwgt_data = BaseRequestTool2.getFormatedDateString();
        HashMap<String, String> hearde = BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, mContext.getString(R.string.h5_trade) +
                TaskConstants.TASK_INVESTETAIL + "?type=" + productBeen.product_type + "&productid=" + productBeen.uuid, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data);
        //添加Url
        String url = getString(R.string.root_h5_url_test) + getString(R.string.h5_trade) + TaskConstants.TASK_INVESTETAIL + "?type=" + productBeen.product_type + "&productid=" + productBeen.uuid;
        detail_webview.loadUrl(url, hearde);


        // TODO: 2017/10/28 这边底下差了一句话导致不能显示，我会将他找出来
        detail_webview.setLayerType(View.LAYER_TYPE_HARDWARE, null);//开启硬件加速
        detail_webview.getSettings().setJavaScriptEnabled(true);
        detail_webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        detail_webview.getSettings().setDefaultTextEncodingName("UTF-8");
        //设置 缓存模式
        detail_webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
//        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        //提高渲染的优先级
        detail_webview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        detail_webview.getSettings().setBuiltInZoomControls(false);
        detail_webview.getSettings().setSupportMultipleWindows(true);
        detail_webview.getSettings().setUseWideViewPort(true);
        detail_webview.getSettings().setLoadWithOverviewMode(true);
        detail_webview.getSettings().setAllowFileAccess(false);
        detail_webview.getSettings().setSupportZoom(false);
        detail_webview.getSettings().setPluginState(WebSettings.PluginState.ON);
        // 开启 DOM storage API 功能
        detail_webview.getSettings().setDomStorageEnabled(true);
        detail_webview.getSettings().setLoadsImagesAutomatically(true);
        detail_webview.getSettings().setSavePassword(false);
        detail_webview.getSettings().setDatabaseEnabled(true);
//      mWebView.getSettings().setBlockNetworkImage(true);
        if (Build.VERSION.SDK_INT >= 21) {
            detail_webview.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        } else {
//            detail_webview.getSettings().setLoadsImagesAutomatically(false);
        }
        detail_webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

        //如果不设置WebViewClient，请求会跳转系统浏览器
        detail_webview.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //该方法在Build.VERSION_CODES.LOLLIPOP以前有效，从Build.VERSION_CODES.LOLLIPOP起，建议使用shouldOverrideUrlLoading(WebView, WebResourceRequest)} instead
                //返回false，意味着请求过程里，不管有多少次的跳转请求（即新的请求地址），均交给webView自己处理，这也是此方法的默认处理
                //返回true，说明你自己想根据url，做新的跳转，比如在判断url符合条件的情况下，我想让webView加载http://ask.csdn.net/questions/178242
                return false;
            }

        });

//        detail_webview.hideBrowserController();

//        ll_product_subject_message = findView(R.id.ll_product_subject_message);
//        ll_invest_record = findView(R.id.ll_invest_record);

        ll_risk_guarantee.setOnClickListener(this);
//        ll_product_detail.setOnClickListener(this);

//        ll_product_subject_message.setOnClickListener(this);
//        ll_invest_record.setOnClickListener(this);

        mPresenter = new InitializePresenterImpl(mContext, this);
        iv_calculator = findView(R.id.iv_calculator);
        iv_calculator.setOnClickListener(this);
        //阀值设置为屏幕高度的1/3
        keyHeight = mScreenHeight / 3;
        linear_botton = findView(R.id.linear_botton);
        if (TextUtils.equals(TAG, "PAY")) {
            linear_botton.setVisibility(View.GONE);
        }
        refreshUI(productBeen);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
//        Logs.e("项目详情的xy值" + ll_product_detail.getX());
    }

    protected void initImmersionBar() {
        super.initImmersionBar();
        mImmersionBar.titleBar(R.id.common_toolbar).init();
    }

    @Override
    protected void onNetworkConnected(NetType type) {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onNetworkDisConnected() {
        // TODO Auto-generated method stub

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * 那边调用setAdapter调用的是这里
     *
     * @param data
     * @param <T>
     */
    @SuppressWarnings("unchecked")
    @Override
    public <T> void setAdapter(List<T> data) {

    }

    /**
     * 网络成功之后的回调
     *
     * @param task_name 任务名称
     * @param result    返回数据
     * @param <T>
     */
    @Override
    public <T> void initializeViews(String task_name, T result) {
        switch (task_name) {
            case TaskConstants.TASK_SETBANKPWD:
                if (result == null) {
                    return;
                }

                UpdatePayPwdBeen mUpdatePayPwdBeen = (UpdatePayPwdBeen) result;

                //现在做另外一种操作
                String postData = null;
                try {
                    postData = "accountId=" + URLEncoder.encode(mUpdatePayPwdBeen.data.accountId.toString(), "utf-8") + "&acqRes=" + URLEncoder.encode(mUpdatePayPwdBeen.data.acqRes.toString(), "utf-8") +
                            "&bankCode=" + URLEncoder.encode(mUpdatePayPwdBeen.data.bankCode.toString(), "utf-8") + "&channel=" + URLEncoder.encode(mUpdatePayPwdBeen.data.channel.toString(), "utf-8") +
                            "&idNo=" + URLEncoder.encode(mUpdatePayPwdBeen.data.idNo.toString(), "utf-8") + "&idType=" + URLEncoder.encode(mUpdatePayPwdBeen.data.idType.toString(), "utf-8") + "&instCode=" +
                            URLEncoder.encode(mUpdatePayPwdBeen.data.instCode.toString(), "utf-8") + "&lastSrvAuthCode=" + URLEncoder.encode(mUpdatePayPwdBeen.data.lastSrvAuthCode == null ? "" : mUpdatePayPwdBeen.data.lastSrvAuthCode.toString(), "utf-8") +
                            "&mobile=" + URLEncoder.encode(mUpdatePayPwdBeen.data.mobile.toString(), "utf-8") + "&name=" + URLEncoder.encode(mUpdatePayPwdBeen.data.name.toString(), "utf-8") + "&notifyUrl=" +
                            URLEncoder.encode(mUpdatePayPwdBeen.data.notifyUrl.toString(), "utf-8") + "&retUrl=" + URLEncoder.encode(mUpdatePayPwdBeen.data.retUrl.toString(), "utf-8") + "&seqNo=" +
                            URLEncoder.encode(mUpdatePayPwdBeen.data.seqNo.toString(), "utf-8") + "&sign=" + URLEncoder.encode(mUpdatePayPwdBeen.data.sign.toString(), "utf-8") + "&smsCode=" +
                            URLEncoder.encode(mUpdatePayPwdBeen.data.smsCode == null ? "" : mUpdatePayPwdBeen.data.smsCode.toString(), "utf-8") + "&txCode=" + URLEncoder.encode(mUpdatePayPwdBeen.data.txCode.toString(), "utf-8") +
                            "&txDate=" + URLEncoder.encode(mUpdatePayPwdBeen.data.txDate.toString(), "utf-8") + "&txTime=" + URLEncoder.encode(mUpdatePayPwdBeen.data.txTime.toString(), "utf-8") + "&version=" +
                            URLEncoder.encode(mUpdatePayPwdBeen.data.version.toString(), "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                Bundle bundle = new Bundle();
                bundle.putString(BaseWebActivity.BUNDLE_KEY_TITLE, getString(R.string.set_paywd));
                bundle.putString(BaseWebActivity.BUNDLE_KEY_URL, mUpdatePayPwdBeen.url);
                bundle.putString(BaseWebActivity.BUNDLE_KEY_PARAMS, postData);
                bundle.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.POSTDATA.getIntValue());
                bundle.putBoolean(BaseWebActivity.BUNDLE_KEY_SHOW_BOTTOM_BAR, false);
                readyGo(WebSetPasswordActivity.class, bundle);
                break;
            case TaskConstants.TASK_BANK_ACCOUNT:
                //查询托管账户信息，更新ui
                BankAccountBeen bankAccountBeen = (BankAccountBeen) result;
                //保存余额信息
//                sharedPreferences.putShareProf(UserInfo.CAN_USE_MONEY, bankAccountBeen.availBal);

                //对江西银行卡信息进行显示
                if (!bankAccountBeen.depository_bank_no.isEmpty()) {//如果返回有银行卡信息，则将银行卡信息保存并且显示银行卡
                    //将获得的银行卡信息保存
                    sharedPreferences.putShareProf(UserInfo.JX_ACCOUNT_NO, bankAccountBeen.depository_bank_no);
                }

                //如果获取了用户的银行卡信息就将其绑定
                /**存储开户信息**/
                if (bankAccountBeen.depository_bank_no != null && !bankAccountBeen.depository_bank_no.isEmpty()) {
                    sharedPreferences.putShareProf(UserInfo.JIANGXI_BANKCARD, bankAccountBeen.depository_bank_no);
                    sharedPreferences.putShareProf(UserInfo.IF_ACCOUNT, "YES");
                } else {
                    sharedPreferences.putShareProf(UserInfo.IF_ACCOUNT, "NO");
                }

                /**存储绑卡信息**/
                if (bankAccountBeen.bankCard != null && !bankAccountBeen.bankCard.isEmpty() && bankAccountBeen.bankName != null && !bankAccountBeen.bankName.isEmpty()) {
                    sharedPreferences.putShareProf(UserInfo.BANKCARD, bankAccountBeen.bankCard);
                    sharedPreferences.putShareProf(UserInfo.BANKCARDNAME, bankAccountBeen.bankName);

                    sharedPreferences.putShareProf(UserInfo.IF_BINDCARD, "YES");
                } else {
                    sharedPreferences.putShareProf(UserInfo.IF_BINDCARD, "NO");
                }

                if (bankAccountBeen.true_name != null && !bankAccountBeen.true_name.isEmpty()) {
                    sharedPreferences.putShareProf(UserInfo.REAL_USER_NAME, bankAccountBeen.true_name);
                }

                /**
                 * 绑定身份证
                 */
                if (bankAccountBeen.cert_no != null && !bankAccountBeen.cert_no.isEmpty()) {
                    sharedPreferences.putShareProf(UserInfo.CERT_NO, bankAccountBeen.cert_no);
                }

                /**保存登陆手机号**/
                //保存手机号码
                if (bankAccountBeen.phone != null && !bankAccountBeen.phone.isEmpty()) {
                    sharedPreferences.putShareProf(UserInfo.MOBILE, bankAccountBeen.phone);
                }

                /*            *//**保存用户交易密码设置状态**/
                if (bankAccountBeen.set_paypwd_flag != null && !bankAccountBeen.set_paypwd_flag.isEmpty()) {
                    if (TextUtils.equals(bankAccountBeen.set_paypwd_flag, "1")) {
                        //已经设置交易密码
                        sharedPreferences.putShareProf(UserInfo.IF_PAYPWD, "YES");
                    } else {
                        sharedPreferences.putShareProf(UserInfo.IF_PAYPWD, "NO");
                    }
                } else {
                    sharedPreferences.putShareProf(UserInfo.IF_PAYPWD, "NO");
                }

                /**保存可用余额**/
                if (bankAccountBeen.availBal != null && !bankAccountBeen.availBal.isEmpty()) {
                    sharedPreferences.putShareProf(UserInfo.CAN_USE_MONEY, bankAccountBeen.availBal);
                }

                //保存用户vip等级
                if (bankAccountBeen.vip != null && !bankAccountBeen.vip.isEmpty()) {
                    sharedPreferences.putShareProf(UserInfo.VIPLEVEL, bankAccountBeen.vip);
                }

                break;
            case TaskConstants.TASK_PAYMENTAUTHDETAIL:
                if (result instanceof AdSlideBeen) {
                    TASK_PAYMENTAUTHDETAIL = false;
                } else {
                    TASK_PAYMENTAUTHDETAIL = true;
                }
                break;
        }
    }

    /**
     * 刷新ui
     *
     * @param info
     */
    private void refreshUI(ProductBeen info) {
        mktGdsName = info.name;
        setToolbarTitle(mktGdsName);

        /**
         * 起投金额
         */
        startMoney = info.invest_min;
//        tv_addmoney.setText(HsNumberUtils.moneyFormat(startMoney));

        /**
         * 投资期限时间+单位
         */
        ivstime = info.term;
        tv_duration_txt.setText(getString(R.string._project_duration, info.getPayMethod(info.pay_method)));
        tv_duration.setText(ivstime);

        /**
         * 项目规模
         */
        tv_scale.setText(info.getDebet());

        /**
         * 年化收益
         */
        tv_percent.setText(CommTool.formart1(Double.valueOf(info.invest_rate)));

//        /**
//         * 剩余可投
//         */
//        tv_surplus_invest.setText(getString(R.string._yuan, info.displayChangeAmount()));

        /**
         * raise_time
         */
        tv_raise_time.setText(CommTool.getTerm(info.raise_time, 0, 10));

        /**
         * start_time
         */
        if (info.start_time != null && !info.start_time.isEmpty()) {
            tv_start_time.setText(info.start_time);
        } else {
            tv_start_time.setText(getString(R.string.amount_day));
        }

        /**
         * end_time
         */
        if (info.end_time != null && !info.end_time.isEmpty()) {
            tv_end_time.setText(info.end_time);
        }

        /**
         * 精选
         */
        if (info.favor_flag != null && !info.favor_flag.isEmpty()) {
            switch (info.favor_flag) {
                case "0":
                    hstv_selected_product.setVisibility(View.GONE);
                    break;
                case "1":
                    hstv_selected_product.setVisibility(View.VISIBLE);
                    break;
            }
        }

        /**
         * 新人专选
         */
        if (TextUtils.equals(info.recruit_flag, "1")) {
            hstv_new_exclusive.setVisibility(View.VISIBLE);
        } else {
            hstv_new_exclusive.setVisibility(View.GONE);
        }
        /**
         * 加息标签显示
         */
        if (info.add_debt_rate != null && MathUtils.compare(info.add_debt_rate, "0") > 0) {
            if (info.add_rate_msg != null) {
                hstv_raise_interest_rate.setText(info.add_rate_msg);
                hstv_raise_interest_rate.setVisibility(View.VISIBLE);
            }
        }

        /**
         * 活动标签显示
         */
        if (info.short_desc != null && !info.short_desc.isEmpty()) {
            hstv_raise_interest_event.setVisibility(View.VISIBLE);
            hstv_raise_interest_event.setText(info.short_desc);
        } else {
            hstv_raise_interest_event.setVisibility(View.GONE);
        }
        /**
         * 底部按钮-- 投资 | 满标 | 停售 | 倒计时
         */
        info.refreshStatus(mContext, btn_buy, invest_progress, info.dispalyProgress(), tv_surplus_invest, info.product_status);//刷新状态

        /**
         * 分险等级
         */
        if (info.risk_level != null && !info.risk_level.isEmpty()) {
            tv_product_risk_level.setText(info.risk_level);
        }

        /**
         * 星级
         */
        switch (info.star_level) {
            case 1:
                rb_product_star.setRating((float) 0.5);
                break;
            case 2:
                rb_product_star.setRating((float) 1);
                break;
            case 3:
                rb_product_star.setRating((float) 1.5);
                break;
            case 4:
                rb_product_star.setRating((float) 2);
                break;
            case 5:
                rb_product_star.setRating((float) 2.5);
                break;
            case 6:
                rb_product_star.setRating((float) 3);
                break;
            case 7:
                rb_product_star.setRating((float) 3.5);
                break;
            case 8:
                rb_product_star.setRating((float) 4);
                break;
            case 9:
                rb_product_star.setRating((float) 4.5);
                break;
            case 10:
                rb_product_star.setRating((float) 5);
                break;
            default:
                rb_product_star.setRating(0);
                break;
        }

        /**
         * 风险描述
         */
        if (info.risk_msg != null && !info.risk_msg.isEmpty()) {
            tv_risk_desc.setText(getString(R.string.risk_tips, info.risk_msg));
        }

        /**
         * 星级描述
         */
        if (info.star_level_desc != null && !info.star_level_desc.isEmpty())
            tv_star_desc.setText(info.star_level_desc);


    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        MobclickAgent.onPageStart("InvestDetailsActivity");
        MobclickAgent.onResume(this);
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        mPresenter.loadingData(TaskConstants.TASK_BANK_ACCOUNT, getString(R.string.root_url_test) + getString(R.string.api_user_test) +
                TaskConstants.TASK_BANK_ACCOUNT, Constants.EVENT_BEGIN, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test)
                + TaskConstants.TASK_BANK_ACCOUNT, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), false);
        //缴费授权详情页
        mPresenter.loadingData(TaskConstants.TASK_PAYMENTAUTHDETAIL, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.TASK_PAYMENTAUTHDETAIL, Constants.EVENT_REFRESH_DATA,
                BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test) + TaskConstants.TASK_PAYMENTAUTHDETAIL, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.
                        getShareProf(UserInfo.TOKENID), zwgt_data), false);
    }

    /**
     * 各个点击事件，弹出计算机什么的
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (isFastDoubleClick()) {
            return;
        }

        switch (v.getId()) {
            case R.id.btn_buy:
                if (sharedPreferences.getShareProf(UserInfo.LENDER).equals("2")
                        || sharedPreferences.getShareProf(UserInfo.LENDER).equals("3")) {
                    new HSToast(mContext).showToast("身份属性不符");
                } else if (!sharedPreferences.getBoolean(UserInfo.ISLOGIN)) {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    mContext.startActivity(intent);
                    showToast(R.string.tips_login);
                } else if (!TextUtils.equals(sharedPreferences.getShareProf(UserInfo.IF_ACCOUNT), "YES")) {//是否开户
                    if (mConfigSP.contains(mContext, UserInfo.BANK_ACCOUNT_INTERFACE_SUCCESS) && !mConfigSP.getBoolean(UserInfo.BANK_ACCOUNT_INTERFACE_SUCCESS)) {
                        showProgressToDismiss();
                        return;
                    }
                    showToast(R.string.open_account);
                    readyGo(ManagementActivity.class);
                } else if (!TextUtils.equals(sharedPreferences.getShareProf(UserInfo.IF_PAYPWD), "YES")) {//交易密码
                    paypwdDialog = new HSDialog(getString(R.string.tips), getString(R.string.tips_nopaypwd),
                            getString(R.string.cancel), getString(R.string.tips_go_set), mContext, this).setCancelable(false);
                    paypwdDialog.show();
                } else if (!TextUtils.equals(sharedPreferences.getShareProf(UserInfo.IF_BINDCARD), "YES")) {// 是否绑卡

                    if (mConfigSP.contains(mContext, UserInfo.BANK_ACCOUNT_INTERFACE_SUCCESS) && !mConfigSP.getBoolean(UserInfo.BANK_ACCOUNT_INTERFACE_SUCCESS)) {
                        showProgressToDismiss();
                        return;
                    }
                    readyGo(ManagementActivity.class);
                    showToast(R.string.bind_card_ever);
                } else if (sharedPreferences.getShareProf(UserInfo.USERLEVEL) != null && TextUtils.equals(sharedPreferences.getShareProf(UserInfo.USERLEVEL), "0")) {
                    dialog = new HSDialog(getString(R.string.risk_login), getString(R.string.no_risk_assessment),
                            getString(R.string.no_investment), getString(R.string.evaluate_immediately), mContext, this).setCancelable(false);
                    dialog.show();
                } else if (!TASK_PAYMENTAUTHDETAIL) {
                    showToast("未进行缴费受权");
                    readyGo(ManagementActivity.class);
                } else {
                    bundle = new Bundle();
                    bundle.putString(Extras.GDSID, productBeen.uuid);
                    bundle.putString(Extras.MKTGDSNAME, productBeen.name);
                    bundle.putString(Extras.RATE, Double.valueOf(productBeen.invest_rate) / 100 + "");
                    bundle.putString(Extras.TERM, productBeen.term);
                    bundle.putString(Extras.PAYMETHOD, productBeen.pay_method);
                    bundle.putString(Extras.INVESTMIN, productBeen.invest_min);
                    bundle.putString(Extras.INVESTMAX, productBeen.invest_max);
                    bundle.putString(Extras.ALLMONEY, productBeen.displayChangeAmount());
                    bundle.putString(Extras.UUID, productBeen.uuid);
                    bundle.putString(Extras.INVESTSTEP, productBeen.invest_step);
                    bundle.putString(Extras.DEBT, productBeen.debt);
                    bundle.putString(Extras.RAISE_AMOUNT, productBeen.raise_amount);
                    bundle.putString(Extras.RECRUIT_FLAG, productBeen.recruit_flag);
                    bundle.putString(Extras.USE_DISCOUNT_FLAG, productBeen.use_discount_flag);
                    readyGo(InvestActivity.class, bundle);
                }
                break;
            case R.id.iv_calculator://弹出计算机
                showPopup(toolbar_title);
                break;
            case R.id.ll_risk_guarantee://风险保障
                zwgt_data = BaseRequestTool2.getFormatedDateString();
                HashMap<String, String> hearder1 = BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, mContext.getString(R.string.h5_trade) +
                        TaskConstants.TASK_RISKPROTECT, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data);
                HeaderMap headerMap1 = new HeaderMap();
                headerMap1.setMap(hearder1);

                bundle = new Bundle();
                bundle.putString(BaseWebActivity.BUNDLE_KEY_TITLE, getString(R.string.risk_protection));
                bundle.putString(BaseWebActivity.BUNDLE_KEY_URL, getString(R.string.root_h5_url_test) + getString(R.string.h5_trade) + TaskConstants.TASK_RISKPROTECT);
                bundle.putSerializable(BaseWebActivity.BUNDLE_KEY_HEADER, headerMap1);
                bundle.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, LoadType.HTTP.getIntValue());
                bundle.putBoolean(BaseWebActivity.BUNDLE_KEY_SHOW_BOTTOM_BAR, false);
                readyGo(WebActivity.class, bundle);
                break;
            case R.id.tv_product_star:
                mIsShowStarDesc = !mIsShowStarDesc;

                if (mIsShowStarDesc) {
                    ll_star_desc.setVisibility(View.VISIBLE);
                } else {
                    ll_star_desc.setVisibility(View.INVISIBLE);
                }

                break;
        }
    }

    @Override
    public <T> void initializeError(String task_name, T data) {
        // TODO Auto-generated method stub

    }

    private void showProgressToDismiss() {
        showProgress("");
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                closeProgress();
            }
        }, 2000);
    }

    /**
     * 防止按钮连续点击
     */
    private static long lastClickTime;

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * 创建PopupWindow对象
     *
     * @param parent
     */
    @SuppressLint("InflateParams")
    private void showPopup(View parent) {
        backgroundAlpha((float) 0.5);
        View view = null;
        if (popWindow == null) {
            LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = layoutInflater.inflate(R.layout.pop_calculator, null);
            calculator = findView(view, R.id.calculator);
            calculator.pay_method = productBeen.pay_method;
            calculator.rate = new BigDecimal(Double.valueOf(productBeen.invest_rate) / 100 + "");
            calculator.term = new BigDecimal(productBeen.term);

            calculator.setDeleteButtonClick(new CalculatorView.OnDeleteButtonListener() {
                @Override
                public void onDeleteButtonClick() {
                    popWindow.dismiss();
                }
            });
            popWindow = new PopupWindow(view, LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT, true);
        }

        // 设置背景，这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
        popWindow.setBackgroundDrawable(getResources().getDrawable(R.color.transparent_66));
        ColorDrawable cd = new ColorDrawable(Color.TRANSPARENT);
        popWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        //popupwindow弹出时的动画
        popWindow.setAnimationStyle(R.style.project_pop_style);
        popWindow.setClippingEnabled(false);
        //软键盘不会挡着popupwindow
        popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //监听菜单的关闭事件
        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
                calculator.setInit();
            }
        });


        popWindow.setTouchable(true);
        // 使其聚集 ，要想监听菜单里控件的事件就必须要调用此方法
        popWindow.setFocusable(true);
        // 设置允许在外点击消失
        popWindow.setOutsideTouchable(true);
//        //监听触屏事件
        popWindow.setTouchInterceptor(new View.OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            public boolean onTouch(View view, MotionEvent event) {
//                if(event.getY()<calculator.getTop() || event.getY()>calculator.getBottom() || event.getX() < calculator.getLeft() || event.getX() > calculator.getRight()){
//                    popWindow.dismiss();
//                    return true;
//                }
                return false;
            }
        });
        popWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    @Override
    public void onItemClick(Object o, int position) {
        if ((HSDialog) o == paypwdDialog) {
            if (position != -1) {
                readyGo(ManagementActivity.class);
            }
        } else if ((HSDialog) o == dialog) {
            if (position != -1) {
                //展示风险评估h5页面
                zwgt_data = BaseRequestTool2.getFormatedDateString();
                HashMap<String, String> hearder = BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, mContext.getString(R.string.h5_user) +
                        TaskConstants.TASK_RISKESTIMATE, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data);
                HeaderMap headerMap = new HeaderMap();
                headerMap.setMap(hearder);
                Bundle bundle = new Bundle();
                bundle.putString(BaseWebActivity.BUNDLE_KEY_TITLE, getString(R.string.risk_estimate));
                bundle.putString(BaseWebActivity.BUNDLE_KEY_URL, getString(R.string.root_h5_url_test) + getString(R.string.h5_user) + TaskConstants.TASK_RISKESTIMATE);
                bundle.putSerializable(BaseWebActivity.BUNDLE_KEY_HEADER, headerMap);
                bundle.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.HTTP.getIntValue());
                bundle.putBoolean(BaseWebActivity.BUNDLE_KEY_SHOW_BOTTOM_BAR, false);
                readyGo(WebRiskActivity.class, bundle);
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("InvestDetailsActivity");
        MobclickAgent.onPause(this);
    }

}
